<?php
namespace App\Components;

use Swoft\Core\Coroutine;

class Memcached
{
    private static $mem;
    private $handle;
    public function getInstance()
    {
        try
        {
            if (self::$mem){
                return self::$mem;
            }
            var_dump(Coroutine::id(),Coroutine::tid());
            $t = microtime();
            Tool::log('链接后前'.$t);
            $config = config('memcache');
            if(empty($config['host']) || empty($config['port']))
            {
                throw new \Exception('Memcached host and port needed!');
            }
            $this->handle = new \Memcached(); //声明一个新的memcached链接

            if(!empty($config['timeout']) && $config['timeout'] > 0)
            {
                $this->handle->setOption(\Memcached::OPT_RECV_TIMEOUT, ((int)$config['timeout']) * 1000);
            }
            $this->handle->setOption(\Memcached::OPT_COMPRESSION, false); //关闭压缩功能
            $this->handle->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);//使用binary二进制协议
            $this->handle->setOption(\Memcached::OPT_TCP_NODELAY, true); //重要，php memcached有个bug，当get的值不存在，有固定40ms延迟，开启这个参数，可以避免这个bug
            $this->handle->addServer($config['host'], $config['port']);//添加OCS实例地址及端口号
            if(!empty($config['user']) && !empty($config['pwd']))
            {
                $this->handle->setSaslAuthData($config['user'], $config['pwd']);//设置OCS帐号密码进行鉴权，如已开启免密码功能，则无需此步骤
            }
            Tool::log('链接后'.$t);
            self::$mem = $this->handle;
            return self::$mem;
        }
        catch (\Exception $e)
        {
            throw new \Exception($e->getMessage());
        }
    }
}